package com.wh.weibo.controller;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.wh.weibo.facade.TopicService;
import com.wh.weibo.facade.WeiboService;
import com.wh.weibo.model.ServiceResult;
import com.wh.weibo.model.Topic;
import com.wh.weibo.model.User;
import com.wh.weibo.model.Weibo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author WeiHong
 * @date 2019/7/11 11:05
 */
@Controller
@RequestMapping("topic")
public class TopicController extends BaseController {

    @Resource
    private TopicService topicService;

    @Resource
    private WeiboService weiboService;

    @Resource
    private RedisTemplate redisTemplate;

    private Cache<Object, Object> topicCache;

    @PostConstruct
    private void init() {
        topicCache = CacheBuilder.newBuilder().initialCapacity(10).maximumSize(100).expireAfterWrite(10, TimeUnit.SECONDS).build();
    }

    @GetMapping("list.html")
    public ModelAndView listHtml() {
        return new ModelAndView("topiclist");
    }

    @GetMapping("get.html")
    public ModelAndView getHtml(@RequestParam(name = "id") Integer topicId) {
        ModelAndView modelAndView = new ModelAndView("gettopic");
        modelAndView.addObject("topicId", topicId);
        return modelAndView;
    }


    @GetMapping("list")
    @ResponseBody
    public Map listTopic() {
        ServiceResult<List<Topic>> serviceResult = topicService.selectList();
        if (null == serviceResult) {
            return getErrorResp("获取微博话题服务异常");
        } else if (!serviceResult.isSuccess()) {
            return getErrorResp(serviceResult.getErrorMsg());
        } else {
            return getResp(serviceResult.getData());
        }
    }


    @GetMapping("get")
    @ResponseBody
    public Map getTopic(@RequestParam(name = "id") Integer id) {

        /*用户阅读操作*/
        User currentUser = this.getCurrentUser();
        if (null != currentUser) {
            try {
                topicService.read(currentUser.getId(), id);
            } catch (Exception e) {

            }
        }

        final String topicKeyPrefix = "topic:detail:";
        String commonKey = topicKeyPrefix + id;

        //优先读取本地缓存
        Map<String, Object> cacheResultMap  = (Map<String, Object>) topicCache.getIfPresent(commonKey);
        if (null != cacheResultMap){
            return getResp(cacheResultMap);
        }

        //读取redis缓存
        Map<String, Object> redisResultMap = (Map<String, Object>) redisTemplate.opsForValue().get(commonKey);
        if (null != redisResultMap) {
            topicCache.put(commonKey, redisResultMap);
            return getResp(redisResultMap);
        }

        Topic topic;
        ServiceResult<Topic> topicServiceResult = topicService.get(id);
        if (null == topicServiceResult) {
            return getErrorResp("获取微博话题服务异常");
        } else if (!topicServiceResult.isSuccess()) {
            return getErrorResp(topicServiceResult.getErrorMsg());
        } else if (null == topicServiceResult.getData()) {
            return getErrorResp("没有话题ID对应的话题");
        } else {
            topic = topicServiceResult.getData();
        }

        List<Weibo> weiboList;
        //查询话题下的所有微博
        ServiceResult<List<Weibo>> listServiceResult = weiboService.selectListByTopicId(topic.getId());
        if (null == listServiceResult) {
            return getErrorResp("获取微博服务异常");
        } else if (!listServiceResult.isSuccess()) {
            return getErrorResp(listServiceResult.getErrorMsg());
        } else {
            weiboList = listServiceResult.getData();
        }
        Map<String, Object> resultMap = new HashMap<>(10);
        resultMap.put("topic", topic);
        resultMap.put("weiboList", weiboList);
        redisTemplate.opsForValue().set(commonKey, resultMap);
        //一定要设置超时时间
        redisTemplate.expire(commonKey, 1, TimeUnit.MINUTES);
        topicCache.put(commonKey, resultMap);
        return getResp(resultMap);

    }


    @PostMapping("create")
    @ResponseBody
    public Map create(@RequestParam(name = "title") String title,
                      @RequestParam(name = "description") String description) {
        if (StringUtils.isAnyBlank(title, description)) {
            return getErrorResp("入参错误");
        }
        Topic topic = new Topic();
        topic.setTitle(title);
        topic.setDescription(description);
        ServiceResult<Topic> serviceResult = topicService.create(topic);
        if (null == serviceResult) {
            return getErrorResp("话题服务通信异常");
        } else if (!serviceResult.isSuccess()) {
            return getErrorResp(serviceResult.getErrorMsg());
        } else {
            return getResp(serviceResult.getData());
        }

    }

    @PostMapping("follow")
    @ResponseBody
    public Map follow(@RequestParam(name = "topicId") Integer topicId) {
        User currentUser = getCurrentUser();
        if (null == currentUser) {
            return getErrorResp("未登陆，无法关注");
        }
        ServiceResult result = topicService.follow(currentUser.getId(), topicId);
        if (null == result) {
            return getErrorResp("话题服务通信异常");
        } else if (!result.isSuccess()) {
            return getErrorResp(result.getErrorMsg());
        } else {
            return getResp(result.getData());
        }
    }


}
